#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_libtevent_libtevent_func_001.py
@Time:      2024/04/23 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_libtevent_libtevent_func_001.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "libtevent libtevent-devel libtalloc-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > tevent_test1.c <<EOF
#include <stdio.h>
#include <tevent.h>
#include <talloc.h>
#include <stdbool.h>

// 事件处理器函数
static void event_handler(struct tevent_context *ev,
                          struct tevent_timer *te,
                          struct timeval current_time,
                          void *private_data)
{
    printf("事件已触发!\\n");

    // 释放定时器
    printf("删除定时器事件\\n");
    TALLOC_FREE(te);

    // 设置退出标志以结束事件循环
    bool *should_exit = (bool *)private_data;
    *should_exit = true;
}

int main(void)
{
    // 创建并初始化事件上下文
    struct tevent_context *ev_ctx = tevent_context_init(NULL);
    if (ev_ctx == NULL) {
        printf("无法初始化tevent上下文\\n");
        return -1;
    }

    // 设置退出事件循环的标志
    bool should_exit = false;

    // 创建一个定时器事件
    struct timeval timeout = tevent_timeval_current_ofs(1, 0); // 1秒后触发
    struct tevent_timer *timer = tevent_add_timer(ev_ctx, NULL, timeout, event_handler, &should_exit);
    if (timer == NULL) {
        printf("无法创建定时器事件\\n");
        TALLOC_FREE(ev_ctx);
        return -1;
    }

    // 处理事件直到没有活动事件为止或退出标志被设置
    printf("开始事件循环...\\n");
    while (!should_exit && (tevent_loop_once(ev_ctx) == 0)) {
        bool should_exit = false;
    }

    // 释放事件上下文资源
    TALLOC_FREE(ev_ctx);

    printf("程序结束\\n");
    return 0;
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o tevent_test1 tevent_test1.c -ltevent -ltalloc')
        code, tevent_result = self.cmd("./tevent_test1")
        self.assertIn('程序结束', tevent_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf tevent_test1.c tevent_test1')
